from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializer import *
from .models import *
import os
from django.conf import settings
from rest_framework.pagination import PageNumberPagination
from rest_framework.generics import *
from rest_framework.mixins import *
# Create your views here.


class MyPagination(PageNumberPagination):
    page_size = 3
    max_page_size = 10

    page_query_param = "page"
    page_size_query_param = "pagesize"


class CateSet(ModelViewSet):
    queryset = Cate.objects.all()
    serializer_class = CateSer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"


# 品牌的视图集
class BrandViewSet(ModelViewSet):
    queryset = Brand.objects.all()
    serializer_class = BrandSer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"

    # pagination_class = MyPagination


# 上传图片的视图类
class UploadBrandLogoAPIView(APIView):
    def post(self, request):
        print("上传图片数据：", request.data, type(request.data))

        # 获取文件对象
        file = request.data.get("file")
        # file.file 上传的文件字节流对象
        # file.name 文件名字

        static_path = "static/images/logos"
        file_path = os.path.join(settings.BASE_DIR, static_path)
        file_name = os.path.join(file_path, file.name)

        # 保存图片
        with open(file_name, "wb") as f:
            f.write(file.file.read())

        return Response({
            "code": 200,
            "msg": "上传图片成功",
            "static_path": static_path,
        })


# 加载所有的频道组数据
class ListChannelAPIView(ListAPIView):
    queryset = Group.objects.all()
    serializer_class = GroupSer
    pagination_class = MyPagination


# 加载所有的商品类别
class CateListAPIView(ListAPIView):
    queryset = Cate.objects.all()
    serializer_class = CateSer


# 更新一个删除一个查看一个频道组
class ChannelInfoAPIView(RetrieveUpdateDestroyAPIView):
    queryset = Group.objects.all()
    serializer_class = GroupSer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"


# 一级分类的视图
class FirstCateAPIView(ListAPIView):
    queryset = Cate.objects.filter(cid=None)
    serializer_class = CateSer


# 增加一个频道组的视图
class AddChannelView(APIView):
    def post(self,request):
        # 接受前端数据
        name = request.data.get("name")
        cate_name = request.data.get("cate_name")
        group_url = request.data.get("group_url")
        sequence = request.data.get("sequence")

        # 2.判断cate_name这个类别是否存在
        cate = Cate.objects.filter(name=cate_name).first()
        if not cate:
            return Response({"code":"400","msg":"添加的类别不存在"})

        # 3.组织下数据
        data = {
            "name": name,
            "cate": cate.id,
            "group_url": group_url,
            "sequence": sequence
        }
        # 4.实例化序列化器对象
        ser = GroupSer(data=data)

        if ser.is_valid():
            ser.save()

            return Response({"code":"200","msg":"添加频道组成功", "data": ser.data})
        else:
            return Response({"code":"400","msg":ser.errors_messages})


# sku的视图集
class SKUViewSet(ModelViewSet):
    queryset = Good.objects.all()
    serializer_class = GoodSer
    lookup_url_kwarg = 'pk'
    lookup_field = 'pk'
    pagination_class = MyPagination


# 获取sku的所有数据
class SKUListAPIView(ListAPIView):
    queryset = Good.objects.all()
    serializer_class = GoodSer


# spu的视图集
class SPUViewSet(ModelViewSet):
    queryset = SPU.objects.all()
    # queryset = SPU.objects.filter(brand=2)
    serializer_class = SPUSer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"
    pagination_class = MyPagination

    # def update(self, request, *args, **kwargs):
    #     spu = self.get_object()
    #     spu.name = request.data.get("name") + "-djx"
    #     spu.brand_id = request.data.get("brand")
    #     spu.category1_id = request.data.get("category1")
    #     spu.category2_id = request.data.get("category2")
    #     spu.category3_id = request.data.get("category3")
    #     spu.desc_detail = request.data.get("desc_detail")
    #     spu.desc_pack = request.data.get("desc_pack")
    #     spu.desc_service = request.data.get("desc_service")
    #     spu.save()
    #     ser = self.get_serializer(spu)
    #
    #     return Response(ser.data)

    # 重写删除的视图
    # def destroy(self, request, *args, **kwargs):
    #
    #     spu = self.get_object()
    #     # 判断要删除的数据是否符合要求
    #     if "小米电视" in spu.name:
    #         self.get_object().delete()
    #         # 返回删除成功的响应
    #         return Response({
    #             "code": 200,
    #             "msg": "删除成功"
    #         })
    #     # 删除的数据不符合要求
    #     else:
    #         return Response({
    #             "code": 200,
    #             "msg": "删除失败，数据不符合要求"
    #         })


class SPUListViewSet(ListAPIView):
    queryset = SPU.objects.all()
    serializer_class = SPUSer


# 加载子级类别
class SubCateAPIView(APIView):
    def get(self, request, pk):
        # 1.查询当前的父级类别
        p_cate = Cate.objects.filter(id=pk).first()

        # 2.查询其子级类别
        subs = p_cate.subs.all()
        ser = CateSer(subs, many=True)

        # 3.返回响应
        return Response(ser.data)


# 获取全部sku数据 添加一个sku数据
# class SKUListCreate(ListCreateAPIView):
#     queryset = Good.objects.all()
#     serializer_class = GoodSer
    # 调用定义好的分页
    # pagination_class = MyPagination


# 删除一个sku数据 更新一个sku数据 获取一个sku数据
# class SKUOneAPIView(RetrieveUpdateDestroyAPIView):
#     queryset = Good.objects.all()
#     serializer_class = GoodSer
#     lookup_field = "pk"


# 规格的视图集
class SPUSpecViewSet(ModelViewSet):
    queryset = SPUSpecification.objects.all()
    # queryset = SPUSpecification.objects.filter(spu__name__contains="小米")
    serializer_class = SPUSpecificationSer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"
    pagination_class = MyPagination

    # 重写添加的视图
    # def create(self, request , *args, **kwargs):
    #     # 获取前端数据
    #     name = request.data.get("name")
    #     spu_id = request.data.get("spu")
    #     spu = SPU.objects.filter(id=spu_id).first()
    #     # 判断添加的数据是否符合要求
    #     if "华为P40" == spu.name:
    #         SPUSpecification.objects.create(name=name, spu_id=spu_id)
    #         # 返回添加成功的响应
    #         return Response({
    #             "code": 200,
    #             "msg": "添加数据成功"
    #         })
    #     # 不符合要求
    #     else:
    #         return Response({
    #             "code": 204,
    #             "msg": "添加的数据不符合要求"
    #         })

    # 重写删除的视图
    # def destroy(self, request, *args, **kwargs):
    #
    #     spu_name = self.get_object()
    #     # 判断要删除的数据是否符合要求
    #     if "小米" in spu_name.spu.name:
    #         self.get_object().delete()
    #         # 返回删除成功的响应
    #         return Response({
    #             "code": 200,
    #             "msg": "删除成功"
    #         })
    #     # 删除的数据不符合要求
    #     else:
    #         return Response({
    #             "code": 200,
    #             "msg": "删除失败，数据不符合要求"
    #         })


class SPUSpecList(ListAPIView):
    queryset = SPUSpecification.objects.all()
    serializer_class = SPUSpecificationSer


# 规格选项值的视图
class SpecOptionSet(ModelViewSet):
    queryset = SpecOption.objects.all()
    serializer_class = SpecOptionSer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"
    pagination_class = MyPagination

    # # 防止重复添加
    # def create(self, request, *args, **kwargs):
    #     # values = request.data.get("value")
    #     specs = request.data.get("spec")
    #     code = SpecOption.objects.filter(spec=specs)  # value=values
    #     if code:
    #         return Response({"code": 204, "msg": "已添加该规格！"})
    #     else:
    #         ser = SpecOptionSer(data=request.data)
    #         ser.is_valid(raise_exception=True)
    #         ser.save()
    #         return Response({"code": 200, "msg": "添加成功！"}, status=201)
    #
    # # 重写删除的方法
    # def destroy(self, request, *args, **kwargs):
    #     spu_name = self.get_object()
    #     # 判断是否符合要求
    #     if "小米" in spu_name.spec.spu.name:
    #         self.get_object().delete()
    #         return Response({"code":200, "msg": "删除成功"})
    #
    #     # 不符合要求
    #     return Response({"code": 204, "msg": "删除的规格不符合要求"})


from rest_framework_jwt.utils import jwt_decode_handler
from jwt.exceptions import ExpiredSignatureError, DecodeError


# 上传商品图片的视图
class UploadSKUImageAPIView(APIView):
    def post(self, request):
        print("上传商品图片的请求:", request.data)

        # 1. 直接获取前端上传的数据
        token = request.data.get("token")
        file = request.data.get("file")

        # 2. token的验证
        try:
            payload = jwt_decode_handler(token)

        except ExpiredSignatureError:
            return Response({"code": 401, "msg": "口令过期"})

        except DecodeError:
            return Response({"code": 401, "msg": "口令错误"})
        # 3.用户已登录， 可以正常上传图片
        file_name = file.name
        static_path = "static/images/goods"
        abs_path = os.path.join(settings.BASE_DIR, static_path)

        # 4.判断目录不存在，创建出来
        if not os.path.exists(abs_path):
            os.makedirs(abs_path)

        # 5.拼接文件名， 打开写入二进制图片数据
        sku_image_path = os.path.join(abs_path, file_name)

        with open(sku_image_path, "wb") as f:
            f.write(file.file.read())

        # 返回响应
        return Response({
            "code": 200,
            "msg": "图片上传成功",
            "static_path": static_path
        })


# 商品图片的视图
class SKUImageViewSet(ModelViewSet):
    queryset = SKUImage.objects.all()
    serializer_class = SKUImageSer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"

    # 防止商品重复添加
    def create(self, request, *args, **kwargs):
        # 1.获取前端的数据
        sku_id = request.data.get("sku")
        image = request.data.get("image")

        # 2.判断该商品是否已添加该图片
        results = SKUImage.objects.filter(sku_id=sku_id, image=image)

        if results:
            return Response({"code": 400, "msg": "该商品已存在"})

        try:
            SKUImage.objects.create(sku_id=sku_id, image=image)
            return Response({"code": 201, "msg": "添加成功"})

        except:
            return Response({"code": 400, "msg": "添加失败"})


# 七牛token的视图
from qiniu import Auth
ak = "L4KBaBkhV52xMvErYgE6XbYDh57uy2qey2qppzRe"
sk = "bildAzQKbSmdtnoAe-dUNjeqM7JMqCWaoURqbaCz"


class QiniuTokenAPIView(APIView):
    def get(self, request):
        # 生成七牛云的token
        token = self.gen_token()

        # 返回响应
        return Response({"code": 200, "token": token})

    @staticmethod
    def gen_token():
        # 实例化鉴权对象
        q = Auth(ak, sk)

        # 生成token
        token = q.upload_token("msdejx")

        # 返回响应
        return token















